﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace POB
{
	class Slot
	{
		private UnitInfo unit;
		private float builtProgress;
		private Player player;

		public SlotState State { get; private set; }
		public float BuildProgess { get { return builtProgress; } }

		Texture2D background;
		Texture2D highlightedBackground;
		Texture2D progressBackground;

		public Slot(Player player)
		{
			this.player = player;
			this.State = SlotState.Empty;
			this.builtProgress = 0f;

			this.progressBackground = player.World.Content.Load<Texture2D>(@"UI\SlotProgress");
			this.background = player.World.Content.Load<Texture2D>(@"UI\SlotBackground");
			this.highlightedBackground = player.World.Content.Load<Texture2D>(@"UI\SlotHighlighted");
		}

		public void StartBuildingUnit(UnitInfo unit)
		{
			if(State != SlotState.Empty)
				throw new InvalidOperationException("Cannot StartBuiltUnit in this Slot, slot allready occupied");

			this.unit = unit;
			this.State = SlotState.InProgress;
			this.builtProgress = 0f;
		}

		public void Update(float elapsedTime)
		{
			if(State == SlotState.InProgress)
			{
				builtProgress += elapsedTime / unit.BuiltTime;
				if(builtProgress > 1 || unit.BuiltTime == 0)
					State = SlotState.UnitReadyToLaunch;
			}
		}

		public void FreeSlot()
		{
			unit = null;
			State = SlotState.Empty;
			this.builtProgress = 0f;
		}

		public void Draw(SpriteBatch batch, Matrix matrix)
		{
			batch.Begin(matrix);

			batch.Draw(background, Vector2.Zero, Color.White);

			if(State == SlotState.InProgress || State == SlotState.UnitReadyToLaunch)
				batch.Draw(progressBackground, Vector2.Zero, new Rectangle(0, 0, (int)((progressBackground.Width - 10) * builtProgress), progressBackground.Height), Color.White);

			if(State == SlotState.UnitReadyToLaunch)
				batch.Draw(highlightedBackground, Vector2.Zero, Color.White);

			string Lable = State == SlotState.Empty ? "Empty" : unit.Name;
			batch.DrawString(player.World.UI36, Lable, new Vector2(player.World.UI36.MeasureString(Lable).X / -2f + 148f, 2f), Color.Black);



			batch.End();
		}
	}

	enum SlotState
	{
		Empty,
		InProgress,
		UnitReadyToLaunch,
	}
}
